#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from datetime import datetime
import time
import random
import logging
import threading
import requests
import json

# 机顶盒上传日志
class WatchLog(threading.Thread):

    def __init__(self, logger, device) :
        super(WatchLog, self).__init__()
        self.logger = logger
        self.device = device

    def run(self) :
        channels = ["cctv1", "cctv2", "cctv4", "cctv3", "cctv5", "cctv6", "cctv7", "cctv8", "cctv9", "cctvkx10",
        "cctvxq11", "cctvsh12", "cctvxw13", "cctvse14", "cctvyy15", "hunws", "btv", "jsws", "zjws", "gdws", "nfws",
        "scws", "hbws", "tjws", "lnws", "cqws", "gxws", "sxws", "shxws", "henws", "ynws", "nhws", "jxws", "jykt",
        "xdkt", "szws", "szdsj", "szcj", "szyl", "szgg", "sdws", "dfws", "szdst", "cctvhd5", "cctvhd1"]

        tenant = {"channel": channels[random.randint(0, len(channels) - 1)], "time": random.randint(0, 480)}

        log = {"logType": "BOOTSTRAP", "mac": self.device["mac"], "deviceClass": self.device["deviceClass"]}
        self.upload(log)
        time.sleep(self.device["periodic"])
        while True:
            log = {"logType": "PERIOD", "tenantName": self.device["tenantName"]}
            self.upload(log)

            log = {"logType": "PLAYING", "tenantName": self.device["tenantName"], "channel": tenant["channel"]}
            self.upload(log)
            timeCount = tenant["time"] - 1
            if timeCount == 0 :
                tenant = {"channel": channels[random.randint(0, len(channels) - 1)], "time": random.randint(0, 480)}
            else :
                tenant["time"] = timeCount
            time.sleep(self.device["periodic"])

    def upload(self, log) :
        log["sn"] = self.device["sn"]
        log["room"] = self.device["room"]
        log["uploadTime"] = self.getNowDate()
        headers = {"Content-Type":"application/json"}
        requests.post("http://101.132.161.95/app/stbLog.do", data=json.dumps(log), headers=headers)
        self.logger.info("[%s] upload [%s] complete" % (log["sn"], log["logType"]))


    def getNowDate(self, timeFormat = "%Y-%m-%d %H:%M:%S"):
        return datetime.now().strftime(timeFormat)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s")
    logger = logging.getLogger()

    lock = threading.Lock()

    devices = [{"sn": "EC88F26CE4651", "mac": "00d0.f811.0001", "deviceClass": "STB100", "room": 101, "tenantName": "小明", "periodic": 180},
    {"sn": "EC88F26CE4684", "mac": "00d0.f811.0002", "deviceClass": "STB100", "room": 102, "tenantName": "小赵", "periodic": 180},
    {"sn": "EC88F26CE477D", "mac": "00d0.f811.0003", "deviceClass": "STB100", "room": 103, "tenantName": "小王", "periodic": 180},
    {"sn": "EC88F26CE4780", "mac": "00d0.f811.0004", "deviceClass": "STB100", "room": 201, "tenantName": "小张", "periodic": 180},
    {"sn": "EC88F26CE4782", "mac": "00d0.f811.0005", "deviceClass": "STB100", "room": 202, "tenantName": "小李", "periodic": 180},
    {"sn": "EC88F26CE478A", "mac": "00d0.f811.0006", "deviceClass": "STB100", "room": 203, "tenantName": "小陈", "periodic": 180},
    {"sn": "EC88F26CE478B", "mac": "00d0.f811.0007", "deviceClass": "STB100", "room": 301, "tenantName": "小红", "periodic": 180}]


    threads = []
    for device in devices:
        thread = WatchLog(logger, device)
        thread.start()
        threads.append(thread)
        time.sleep(10)

    for thread in threads :
        thread.join()
